package com.rimi.bbs.handler;

import com.rimi.bbs.bean.JsonResult;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登陆失败的响应
 */
@Component
public class MyAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.info("登录失败"+exception);
        response.setContentType("application/json;charset=UTF-8");
        if(exception instanceof UsernameNotFoundException){
            response.getWriter().write(JsonResult.error("用户名或密码错误").toString());
            return;
        }
        if(exception instanceof LockedException){
            response.getWriter().write(JsonResult.error("该账户已被锁定").toString());
            return;
        }
        response.getWriter().write(JsonResult.error("登录信息验证失败").put("exception",exception).toString());
    }
}
